package org.rayken.trix.commons.game.runTypes;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.rayken.trix.commons.card.Card;
import org.rayken.trix.commons.game.Game;
import org.rayken.trix.commons.game.Play;
import org.rayken.trix.commons.game.Player;
import org.rayken.trix.commons.game.Run;
import org.rayken.trix.commons.game.RunType;
import org.rayken.trix.commons.game.Trick;

public class TheLastFoolRun extends Run {

	static final int PENALTY_SCORE = 100;
	// In the case of capot, all the other players get a penalty of
	// CAPOT_PENALTY_SCORE
	static final int CAPOT_PENALTY_SCORE = PENALTY_SCORE;

	private Map<Player, Integer> tricksWon = new HashMap<Player, Integer>();

	protected TheLastFoolRun(Game game, Player caller, boolean forced) {
		super(game, caller, forced);
		for (Player p : game.getPlayers())
			tricksWon.put(p, 0);
	}

	@Override
	public boolean isFinished() {
		return isComplete();
	}

	@Override
	public RunType getType() {
		return RunType.THE_LAST_FOOL;
	}

	@Override
	public void cardPlayed(Player player, Trick trick, Card cardPlayed) {
		if (trick.isComplete()) {
			Play winningPlay = trick.getWiningPlay();
			Player winningPlayer = winningPlay.getPlayer();
			tricksWon.put(winningPlayer, tricksWon.get(winningPlayer) + 1);
			if (super.isComplete()) {// last trick
				// check for capot
				if (tricksWon.get(winningPlayer) == 8) {
					// capot
					int scoreToAdd = CAPOT_PENALTY_SCORE;
					if (forced)
						scoreToAdd *= 2;
					for (Player victim : game.getPlayers()) {
						if (!winningPlayer.equals(victim))
							if (victim.equals(caller))
								addScore(victim, scoreToAdd * 2);
							else
								addScore(victim, scoreToAdd);
					}
				} else {
					int scoreToAdd = PENALTY_SCORE;
					if (forced)
						scoreToAdd *= 2;
					if (winningPlayer.equals(caller))
						scoreToAdd *= 2;
					addScore(winningPlayer, scoreToAdd);
				}
			}
		}
		deals.get(player).remove(cardPlayed);
	}

	@Override
	public List<Card> getAvailablePlayableCard(Player player, Trick turn) {
		return super.getAvailablePlayableCardDefault(player, turn);
	}

}
